package org.anachronos.jeep.ui.trace.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.anachronos.jeep.model.trace.SqlStatementExecution;
import org.eclipse.jface.viewers.StyledString;

public class SqlStatementStyler {
	private static final Pattern SELECT_STATEMENT_PATTERN = 
		Pattern.compile("(select ).*( from .* )where .*", Pattern.CASE_INSENSITIVE);
	private static final Pattern INSERT_STATEMENT_PATTERN = 
		Pattern.compile("(insert into .* )values.*", Pattern.CASE_INSENSITIVE);

	private SqlStatementStyler() {
		// prevent instantiation
	}
	
	public static StyledString getStyledStatement(final SqlStatementExecution sqlStatementExecution) {
		final String statement = sqlStatementExecution.getStatement();
		final Matcher selectMatcher = SELECT_STATEMENT_PATTERN.matcher(statement);
		final StyledString styledString;
		if (selectMatcher.matches()) {
			final String select = selectMatcher.group(1);
			final String from = selectMatcher.group(2);
			styledString = new StyledString(select)
				.append("\u2026", StyledString.DECORATIONS_STYLER)
				.append(from)
				.append("\u2026", StyledString.DECORATIONS_STYLER);
			
		} else {
			final Matcher insertMatcher = INSERT_STATEMENT_PATTERN.matcher(statement);
			if (insertMatcher.matches()) {
				final String insert = insertMatcher.group(1);
				styledString = new StyledString(insert)
					.append("\u2026", StyledString.DECORATIONS_STYLER);
			} else {
				styledString = new StyledString(statement);
			}
		}
		return styledString;
	}
}
